package com.ujoku.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.labillusion.core.platform.web.rest.RESTController;
import com.ujoku.context.ActionContext;
import com.ujoku.domain.CMSContent;
import com.ujoku.domain.Favorite;
import com.ujoku.domain.Goods;
import com.ujoku.domain.Visitor;
import com.ujoku.service.CMSContentService;
import com.ujoku.service.FavoriteService;
import com.ujoku.service.GoodsService;
import com.ujoku.view.builder.ActivityViewBuilder;
import com.ujoku.view.domain.ActivityView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by Andy.Lian on 2015/3/10.
 */
@Controller
public class ActivityController extends RESTController {
    @Autowired
    protected CMSContentService cmsContentService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ActivityViewBuilder activityViewBuilder;
    @Autowired
    private ActionContext actionContext;
    @Autowired
    private FavoriteService favoriteService;

    @RequestMapping(value = "/activity", method = RequestMethod.POST)
    @ResponseBody
    public ActivityView getActivityView() throws Exception {
        CMSContent content=cmsContentService.selectActivtyContent();
        if(content==null){
            return null;
        }
        ActivityView activityView=new ActivityView();
        try{
            ObjectMapper objectMapper=new ObjectMapper();
            activityView=objectMapper.readValue(content.getContent(), ActivityView.class);
        }catch (Exception e) {
            e.printStackTrace();
        }

        List<Goods> list = goodsService.selectList();
        List<Favorite> favoriteList=getFavoriteList();
        activityViewBuilder.ActivityViewBuilder(activityView,list, favoriteList,content.getUpdateTime());
        return activityView;
    }

    private List<Favorite> getFavoriteList(){
        Visitor visitor = actionContext.getCurrentVisitor();
        if(visitor==null || visitor.getUser_id() == null){
            return null;
        }

        List<Favorite> favoriteList=favoriteService.getFavoritesByUserId(visitor.getUser_id());
        return favoriteList;
    }
}
